const common = {
	getState: function() {
		let autor = uni.getStorageSync("autor");
		if (autor) {
			return {autor};
		} else {
			uni.redirectTo({
				url: "../pages/first"
			});
		}
	},
	setAttribute: function(key, value) {
		uni.setStorageSync(key, value);
	},
	getAttribute: function(key) {
		return uni.getStorageSync(key);
	},
	toJson: (object) => {
		return JSON.stringify(object);
	},
	toObject: (valString) => {
		return JSON.parse(valString);
	},
	deepClone: (object) => {
		return common.toObject(common.toJson(object));
	},
	compareObjectDeep: (val1, val2) => {
		return common.toJson(val1) === common.toJson(val2);
	},
	getQueryVariable: function(variable) {
		var query = window.location.search.substring(1);
		var vars = query.split("&");
		for (var i = 0; i < vars.length; i++) {
			var pair = vars[i].split("=");
			if (pair[0] == variable) {
				return pair[1];
			}
		}
		return (false);
	},
	//转换金额格式 10,000.00
	//money=金额
	//n=保留小数位数 默认2位
	parseMoney: function(money, n) {
		if (money == 'undefined' || money == null || money == '0' || money == undefined || money == "" ||
			parseFloat(money) == 0) {
			return '0.00';
		} else {
			if (money > 0) { //金额为大于0
				n = n > 0 && n <= 20 ? n : 2;
				money = parseFloat((money + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
				var l = money.split(".")[0].split("").reverse();
				var r = money.split(".")[1];
				var t = "";
				for (let i = 0; i < l.length; i++) {
					t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
				}
				return t.split("").reverse().join("") + "." + r;
			} else { //金额小于0
				n = n > 0 && n <= 20 ? n : 2;
				money = parseFloat((money + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
				var l = money.split(".")[0].split("").reverse();
				l.pop();
				var r = money.split(".")[1];
				var t = "";
				for (let i = 0; i < l.length; i++) {
					t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
				}
				return '-' + t.split("").reverse().join("") + "." + r;
			}
		}
	}
};

export default common;
